<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-row>
          <el-form-item label="项目编号:" label-width="82px">
            <el-input v-model="query.projectCode" clearable placeholder="项目编号" size="small"></el-input>
          </el-form-item>
          <el-form-item label="审计类型:" label-width="82px">
            <el-select v-model="query.auditType" clearable>
              <el-option v-for="dict in dict.type.audit_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目进度:" label-width="82px">
            <el-select v-model="query.projectProgress" clearable filterable placeholder="项目进度">
              <el-option
                v-for="item in dict.type.project_progress"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="项目名称:" label-width="82px">
            <el-input v-model="query.projectName" clearable placeholder="项目名称" size="small"></el-input>
          </el-form-item>
          <el-form-item label="审批状态:" label-width="82px">
            <el-select v-model="query.auditStatus" clearable>
              <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年度:" label-width="82px">
            <el-select v-model="query.projectYear" clearable>
              <el-option v-for="planHeadYear in planHeadYears" :key="planHeadYear" :label="planHeadYear" :value="planHeadYear"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button :loading="loading" icon="el-icon-search" size="small" type="primary" @click="onSearch">搜索
            </el-button>
            <el-button :loading="loading" icon="el-icon-delete" size="small" @click="searchReset">清空</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="btn-operate">
        <el-button icon="el-icon-plus" type="primary" @click="addOrUpdateHandle()">
          项目立项
        </el-button>
      </div>
      <el-table v-loading="loading" :data="data" border
                header-row-class-name="container-table-header"
                row-key="projectId" size="small" stripe
                highlight-current-row @cell-click="handleCellClick"
                style="width: 100%;margin-bottom: 20px;">
        <el-table-column label="年度" prop="projectYear" width="80">
        </el-table-column>
        <el-table-column label="项目编号" prop="projectCode" width="125">
        </el-table-column>
        <el-table-column label="项目名称" prop="projectName">
        </el-table-column>
        <el-table-column label="被审计单位" prop="auditedCompanyName">
        </el-table-column>
        <el-table-column label="审计类型" prop="effectiveDate" >
          <template slot-scope="scope">
            <DictTag :options="dict.type.audit_type" :value="scope.row.auditType"></DictTag>
          </template>
        </el-table-column>
        <el-table-column label="项目进度" prop="projectProgress" width="100">
          <template slot-scope="scope">
            <DictTag :options="dict.type.project_progress" :value="scope.row.projectProgress"></DictTag>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" prop="auditStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.auditStatus | auditStatusTag">{{ scope.row.auditStatus | auditStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button v-if="permissions.project_project_get" type="text" size="small" icon="el-icon-view" @click="showViewBox(scope.row)">查看</el-button>
            <el-button v-if="permissions.project_project_add && (scope.row.auditStatus === 0 || scope.row.auditStatus === 2)" icon="el-icon-edit" size="small" type="text" @click="addOrUpdateHandle(scope.row)">项目调整</el-button>
            <el-button v-if="scope.row.taskId" type="text" size="small" icon="el-icon-edit" @click="showTaskAuditTaskDialog(scope.row)">审批</el-button>
            <el-button v-if="scope.row.auditStatus > 0" type="text" size="small" icon="el-icon-view" @click="showTaskAuditLogDialog(scope.row)">审批日志</el-button>
            <el-button v-if="permissions.project_project_del" type="text" size="small" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination
          :current-page="page.current"
          :page-size="10"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChange"
          @current-change="currentChange">
        </el-pagination>
      </div>
    </div>

    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewBox"
               :append-to-body="true" :before-close="closeViewBox" width="1200px">
      <ProjectAuditView :params="form" :management="isManagement"></ProjectAuditView>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" size="small" @click="closeViewBox">关闭</el-button>
      </span>
    </el-dialog>

    <table-form ref="addOrUpdate" @cancelDialog="closeProjectDialog"></table-form>
    <TaskAuditDialog :dialog="taskAuditDialog" @setValue="setTaskAuditTaskDialog" @closeDialog="closeTaskAuditTaskDialog" ref="taskAuditDialog" />
    <TaskAuditLogDialog :dialog="taskAuditLogDialog" :process-id="processId" @closeDialog="closeTaskAuditTaskLogDialog"/>
  </basic-container>
</template>
<script>
import {mapGetters} from "vuex";
import Tinymce from '@/components/Tinymce'
import TableForm from "@/components/form/projectForm";
import Template from "@/views/adis/base/template";
import TaskAuditDialog from "@/components/act/TaskAuditDialog";
import TaskAuditLogDialog from "@/components/act/TaskAuditLogDialog";
import ProjectAuditView from "@/components/actForm/ProjectAuditView";
import {listPlanHeadYear} from "@/api/adis/work/plan";
import {delObj, fetchProjectList, getProject} from "@/api/adis/project/project";

export default {
  directives: {},
  components: {
    ProjectAuditView,
    Template,
    Tinymce,
    TableForm,
    TaskAuditDialog,
    TaskAuditLogDialog,
  },
  dictTypes: ['audit_type', 'project_progress', 'audit_status'],
  data() {
    return {
      isManagement: false,
      viewBox: false,
      formBox: false,
      formTitle: '',
      loading: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      taskAuditDialog: false,
      taskAuditLogDialog: false,
      processId: '',
      query: {},
      form: {},
      planHeadYears: [],
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      selectionRow: [],
      fileList: [], // 文件
    }
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"])
  },
  created() {
    if(this.$route.query && this.$route.query.id) {
      if(this.$route.query.message) {
        this.showViewBox({projectId: this.$route.query.id});
      }
      if(this.$route.query.task) {

      }
    }
    this.onLoad(this.page);
  },
  watch: {

  },
  methods: {
    // 获取所有已经审批通过的年度计划年度
    listPlanHeadYear(){
      listPlanHeadYear().then((res) => {
        this.$set(this,"planHeadYears", res.data.data)
      });
    },

    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row)
      }
    },

    // 新增 / 修改
    addOrUpdateHandle (row) {
      const Edit = row ?
        { projectId: row.projectId, showEdit: true } :
        { compilerId: this.userInfo.userId, compiler: this.userInfo.realname, showEdit: false };
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(Edit)
      })
    },
    closeProjectDialog() {
      this.onLoad(this.page);
    },
    showUserDialog(arr, type, multiple) {
      this.transferDialogTypeArr = arr
      this.transferDialogType = type
      this.multiple = multiple
      this.transferDialog = true
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentVal = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentVal.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentVal = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogTypeArr[0], currentLabel.join(','))
        this.$set(this.form, this.transferDialogTypeArr[1], currentVal.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogTypeArr[0], '')
        this.$set(this.form, this.transferDialogTypeArr[1], '')
      }
      this.transferDialogType = ''
    },
    showEditBox(row) {
      getProject(row.projectId).then((res) => {
        this.form = res.data.data;
        if (res.data.data.fileUrl) {
          this.fileList.push({url: res.data.data.fileUrl});
        }
        const dateFields = ['audit', 'project', 'work', 'prepare', 'apply', 'finish'];

        dateFields.forEach(field => {
          const StartDate = this.form[`${field}StartDate`];
          const EndDate = this.form[`${field}EndDate`];
          this.form[`${field}Dates`] = []
          if (StartDate && EndDate) {
            this.form[`${field}Dates`].push(StartDate);
            this.form[`${field}Dates`].push(EndDate);
          }
        });
        this.formTitle = row.projectName;
        this.formBox = true;
      });
    },
    showViewBox(row) {
      getProject(row.projectId).then((projectResponse) => {
        this.form = projectResponse.data.data;
        this.formTitle = row.projectName;
        this.viewBox = true;
      });
    },
    closeViewBox() {
      this.viewBox = false;
    },
    handleDelete(row) {
      this.$confirm("确定将选择的数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delObj(row.projectId);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.isEngineering = false;
      this.query.isTermination = false;
      fetchProjectList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.listPlanHeadYear()
      }, () => {
        this.loading = false;
      });
    },

    /**=========审批相关==begin===========*/
    showTaskAuditTaskDialog(row) {
      this.taskAuditDialog = true;
      this.$refs['taskAuditDialog'].initData({taskId: row.taskId, processId: row.processId});
    },
    closeTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
    },
    setTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
      this.onLoad(this.page);
    },
    showTaskAuditLogDialog(row) {
      this.processId = row.processId;
      this.taskAuditLogDialog = true;
    },
    closeTaskAuditTaskLogDialog() {
      this.taskAuditLogDialog = false;
    },
    /**=========审批相关==end===========*/

    downloadWord: function(row) {
      this.downBlobFile(
        "/exam/project/project/downloadWord/"+ row.projectId,
        {},
        row.projectName + ".docx"
      )
    },
  }
};
</script>

<style>
.el-select-dropdown {
  overflow-y: auto;
}
</style>
